<template>
  <div class="admin-users">
    <el-card>
      <template #header>
        <div class="card-header">
          <h2>用户管理</h2>
          <div class="header-actions">
            <el-button type="primary" @click="handleAddUser">新增用户</el-button>
          </div>
        </div>
      </template>
      
      <div class="table-toolbar">
        <el-form :inline="true" class="search-form">
          <el-form-item>
            <el-input
              v-model="searchQuery"
              placeholder="搜索用户名/昵称/邮箱"
              clearable
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-select v-model="roleFilter" placeholder="角色" clearable>
              <el-option label="普通用户" value="USER" />
              <el-option label="管理员" value="ADMIN" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-select v-model="statusFilter" placeholder="状态" clearable>
              <el-option label="正常" value="ACTIVE" />
              <el-option label="禁用" value="DISABLED" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <el-table
        :data="tableData"
        v-loading="loading"
        border
        style="width: 100%"
      >
        <el-table-column type="index" width="50" />
        <el-table-column label="头像" width="70">
          <template #default="scope">
            <el-avatar :size="40" :src="scope.row.avatarUrl || defaultAvatarUrl"></el-avatar>
          </template>
        </el-table-column>
        <el-table-column prop="username" label="用户名" width="120" sortable />
        <el-table-column prop="nickname" label="昵称" width="120" />
        <el-table-column prop="email" label="邮箱" width="180" />
        <el-table-column prop="role" label="角色" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.isAdmin === 1 || scope.row.role === 'ADMIN' ? 'danger' : 'info'">
              {{ scope.row.isAdmin === 1 || scope.row.role === 'ADMIN' ? '管理员' : '普通用户' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="(scope.row.state === 0 || scope.row.status === 'ACTIVE') ? 'success' : 'info'">
              {{ (scope.row.state === 0 || scope.row.status === 'ACTIVE') ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="注册时间" width="180" sortable />
        <el-table-column label="操作" fixed="right" width="240">
          <template #default="scope">
            <el-button size="small" @click="handleEditUser(scope.row)">编辑</el-button>
            <el-button 
              size="small" 
              :type="scope.row.status === 'ACTIVE' ? 'warning' : 'success'"
              @click="handleToggleStatus(scope.row)"
            >
              {{ scope.row.status === 'ACTIVE' ? '禁用' : '启用' }}
            </el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="handleDeleteUser(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 用户编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增用户' : '编辑用户'"
      width="500px"
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="userRules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" :disabled="dialogType === 'edit'"></el-input>
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="userForm.nickname"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="dialogType === 'add'">
          <el-input v-model="userForm.password" type="password" show-password></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="passwordRepeat" v-if="dialogType === 'add'">
          <el-input v-model="userForm.passwordRepeat" type="password" show-password></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="userForm.role" placeholder="请选择角色">
            <el-option label="普通用户" value="USER"></el-option>
            <el-option label="管理员" value="ADMIN"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="userForm.status" placeholder="请选择状态">
            <el-option label="正常" value="ACTIVE"></el-option>
            <el-option label="禁用" value="DISABLED"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitUserForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import api from '@/api'
import { normalizeAvatarUrl, getDefaultAvatarUrl } from '@/utils/imageUtils'

export default {
  name: 'AdminUsers',
  
  setup() {
    // 表格数据和加载状态
    const tableData = ref([])
    const loading = ref(true)
    
    // 获取默认头像URL
    const defaultAvatarUrl = getDefaultAvatarUrl()
    
    // 分页参数
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)
    
    // 搜索过滤条件
    const searchQuery = ref('')
    const roleFilter = ref('')
    const statusFilter = ref('')
    
    // 对话框状态
    const dialogVisible = ref(false)
    const dialogType = ref('add') // 'add' 或 'edit'
    const userFormRef = ref(null)
    
    // 表单数据
    const userForm = reactive({
      id: '',
      username: '',
      nickname: '',
      email: '',
      password: '',
      passwordRepeat: '',
      role: 'USER',
      status: 'ACTIVE'
    })
    
    // 表单验证规则
    const userRules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '长度应为3到20个字符', trigger: 'blur' }
      ],
      nickname: [
        { required: true, message: '请输入昵称', trigger: 'blur' },
        { min: 2, max: 20, message: '长度应为2到20个字符', trigger: 'blur' }
      ],
      email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 20, message: '长度应为6到20个字符', trigger: 'blur' }
      ],
      passwordRepeat: [
        { required: true, message: '请确认密码', trigger: 'blur' },
        { validator: (rule, value) => {
          if (value !== userForm.password) {
            return Promise.reject('两次输入的密码不一致')
          }
          return Promise.resolve()
        }, trigger: 'blur' }
      ],
      role: [
        { required: true, message: '请选择角色', trigger: 'change' }
      ],
      status: [
        { required: true, message: '请选择状态', trigger: 'change' }
      ]
    }
    
    // 处理API返回的用户数据，标准化字段
    const processUserData = (users) => {
      return users.map(user => {
        // 创建一个标准化的用户对象
        return {
          id: user.id,
          username: user.username,
          nickname: user.nickname || user.username,
          email: user.email || '',
          // 处理头像路径 - 使用normalizeAvatarUrl确保URL有效
          avatarUrl: normalizeAvatarUrl(user.avatarUrl),
          // 处理角色信息: 将isAdmin=1转换为role='ADMIN'
          role: user.isAdmin === 1 ? 'ADMIN' : 'USER',
          // 映射原始字段以便模板访问
          isAdmin: user.isAdmin,
          // 处理状态信息: 将state=0转换为status='ACTIVE'
          status: user.state === 0 ? 'ACTIVE' : 'DISABLED',
          // 映射原始字段以便模板访问
          state: user.state,
          createTime: user.createTime || ''
        }
      })
    }
    
    // 获取用户列表
    const fetchUsers = async () => {
      loading.value = true
      try {
        // 构建API请求参数
        const params = {
          page: currentPage.value,
          size: pageSize.value,
          keyword: searchQuery.value,
          role: roleFilter.value,
          status: statusFilter.value
        }
        
        // 调用API获取用户列表
        const response = await api.admin.getUserList(params)
        console.log('获取用户列表响应:', response)
        
        if (response && response.code === 0) {
          // 检查响应数据结构
          if (response.data && Array.isArray(response.data)) {
            // 直接是数组
            tableData.value = processUserData(response.data)
            total.value = response.total || response.data.length
          } else if (response.data && response.data.list && Array.isArray(response.data.list)) {
            // 标准分页格式
            tableData.value = processUserData(response.data.list)
            total.value = response.data.total || response.data.list.length
          } else if (response.data && typeof response.data === 'object') {
            // 尝试从响应中获取用户数据
            const userData = Object.values(response.data).filter(item => 
              item && typeof item === 'object' && item.username
            )
            if (userData.length > 0) {
              tableData.value = processUserData(userData)
              total.value = userData.length
            } else {
              tableData.value = []
              total.value = 0
              console.warn('响应数据格式不符合预期:', response.data)
            }
          } else {
            tableData.value = []
            total.value = 0
            console.warn('响应数据格式不符合预期:', response.data)
          }
        } else {
          tableData.value = []
          total.value = 0
          ElMessage.warning(response?.message || '获取数据失败')
        }
      } catch (error) {
        console.error('获取用户列表失败:', error)
        ElMessage.error('获取用户列表失败')
      } finally {
        loading.value = false
      }
    }
    
    // 搜索处理
    const handleSearch = () => {
      currentPage.value = 1
      fetchUsers()
    }
    
    // 重置搜索条件
    const resetSearch = () => {
      searchQuery.value = ''
      roleFilter.value = ''
      statusFilter.value = ''
      currentPage.value = 1
      fetchUsers()
    }
    
    // 分页处理
    const handleSizeChange = (size) => {
      pageSize.value = size
      fetchUsers()
    }
    
    const handleCurrentChange = (page) => {
      currentPage.value = page
      fetchUsers()
    }
    
    // 新增用户
    const handleAddUser = () => {
      dialogType.value = 'add'
      resetUserForm()
      dialogVisible.value = true
    }
    
    // 编辑用户
    const handleEditUser = (row) => {
      dialogType.value = 'edit'
      userForm.id = row.id
      userForm.username = row.username
      userForm.nickname = row.nickname
      userForm.email = row.email
      userForm.role = row.role
      userForm.status = row.status
      dialogVisible.value = true
    }
    
    // 切换用户状态
    const handleToggleStatus = (row) => {
      const action = row.status === 'ACTIVE' ? '禁用' : '启用'
      ElMessageBox.confirm(`确定要${action}该用户吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await api.admin.toggleUserStatus(row.id, row.status)
          // 更新本地状态
          row.status = row.status === 'ACTIVE' ? 'DISABLED' : 'ACTIVE'
          ElMessage.success(`${action}成功`)
        } catch (error) {
          console.error('操作失败:', error)
          ElMessage.error('操作失败: ' + (error.message || '未知错误'))
        }
      }).catch(() => {})
    }
    
    // 删除用户
    const handleDeleteUser = (row) => {
      ElMessageBox.confirm('删除用户将无法恢复，是否继续?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await api.admin.deleteUser(row.id)
          ElMessage.success('删除成功')
          fetchUsers() // 刷新列表
        } catch (error) {
          console.error('删除失败:', error)
          ElMessage.error('删除失败: ' + (error.message || '未知错误'))
        }
      }).catch(() => {})
    }
    
    // 重置表单
    const resetUserForm = () => {
      userForm.id = ''
      userForm.username = ''
      userForm.nickname = ''
      userForm.email = ''
      userForm.password = ''
      userForm.passwordRepeat = ''
      userForm.role = 'USER'
      userForm.status = 'ACTIVE'
      
      if (userFormRef.value) {
        userFormRef.value.resetFields()
      }
    }
    
    // 提交表单
    const submitUserForm = () => {
      userFormRef.value.validate(async (valid) => {
        if (valid) {
          try {
            if (dialogType.value === 'add') {
              // 新增用户
              await api.admin.createUser(userForm)
              ElMessage.success('新增用户成功')
            } else {
              // 编辑用户
              await api.admin.updateUserByAdmin(userForm.id, userForm)
              ElMessage.success('编辑用户成功')
            }
            
            dialogVisible.value = false
            fetchUsers() // 刷新列表
          } catch (error) {
            console.error('操作失败:', error)
            ElMessage.error('操作失败: ' + (error.message || '未知错误'))
          }
        }
      })
    }
    
    onMounted(() => {
      // 避免重复请求，只在组件挂载时请求一次
      setTimeout(() => {
        fetchUsers()
      }, 100) // 添加短暂延迟防止重复触发
    })
    
    return {
      tableData,
      loading,
      currentPage,
      pageSize,
      total,
      searchQuery,
      roleFilter,
      statusFilter,
      dialogVisible,
      dialogType,
      userFormRef,
      userForm,
      userRules,
      handleSearch,
      resetSearch,
      handleSizeChange,
      handleCurrentChange,
      handleAddUser,
      handleEditUser,
      handleToggleStatus,
      handleDeleteUser,
      submitUserForm,
      defaultAvatarUrl,
      normalizeAvatarUrl
    }
  }
}
</script>

<style scoped>
.admin-users {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  font-size: 20px;
}

.table-toolbar {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 